package com.scraper.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.scraper.dao.BaseDAO;

public class BaseDAOImpl<T extends Serializable> extends HibernateDaoSupport implements BaseDAO<T> {

	@SuppressWarnings("unchecked")
	final Class entityClass;

	@SuppressWarnings("unchecked")
	public BaseDAOImpl(Class entityClass) {
		this.entityClass = entityClass;
	}

	@Transactional(readOnly = false)
	public void delete(T entity) {
		getSession().delete(entity);
		getSession().flush();
	}

	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> list() {
		return getSession().createCriteria(entityClass).list();
	}

	@SuppressWarnings("unchecked")
	public List<T> list(String property, Object value) {
		return list(property, value, null);
	}

	@SuppressWarnings("unchecked")
	public List<T> list(String property, Object value, String sortedProperty) {
		Criteria criteria = getSession().createCriteria(entityClass).add(Restrictions.eq(property, value));
		if (sortedProperty != null)
			criteria.addOrder(Order.asc(sortedProperty));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> listSortedAsc(String property) {
		return getSession().createCriteria(entityClass).addOrder(Order.asc(property)).list();
	}

	@Transactional(readOnly = false)
	public void merge(T entity) {
		getSession().merge(entity);
		getSession().flush();

	}

	public void refresh(T entity) {
		getHibernateTemplate().refresh(entity);
	}

	@Transactional(readOnly = false)
	public void saveOrUpdate(T entity) {

		getSession().saveOrUpdate(entity);
		getSession().flush();
	}

}
